import { utils, writeFile } from "xlsx";
import { message } from "./message";
import type { TableColumn } from "@pureadmin/table";
import dayjs from "dayjs";
export class CommonUtils {
  // static fillPaginationParams(
  //   baseQuery: BasePageQuery,
  //   pagination: PaginationProps
  // ) {
  //   baseQuery.pageNum = pagination.currentPage;
  //   baseQuery.pageSize = pagination.pageSize;
  // }
  static base64ToBlob(base64String, mimeType = "image/jpeg"): Blob {
    // 将base64字符串中的dataURL头部信息去掉，只保留纯base64编码数据
    const base64WithoutPrefix = base64String.replace(
      /^data:image\/\w+;base64,/,
      ""
    );

    // 使用atob将base64编码转换为二进制数据
    const binaryData = atob(base64WithoutPrefix);

    // 构建Blob对象，mimeType根据实际情况调整
    const arrayBuffer = new ArrayBuffer(binaryData.length);
    const uint8Array = new Uint8Array(arrayBuffer);

    for (let i = 0; i < binaryData.length; i++) {
      uint8Array[i] = binaryData.charCodeAt(i);
    }

    return new Blob([arrayBuffer], { type: mimeType });
  }
  static exportExcel(
    columns: TableColumnList,
    originalDataList: any[],
    excelName: string
  ) {
    if (
      !Array.isArray(columns) ||
      !Array.isArray(originalDataList) ||
      typeof excelName !== "string"
    ) {
      message("参数异常，导出失败", { type: "error" });
      return;
    }

    // columns和dataList为空的话 弹出提示 不执行导出
    if (columns.length === 0 || originalDataList.length === 0) {
      message("无法导出空列表", { type: "warning" });
      return;
    }

    const titleList: string[] = [];
    const dataKeyList: string[] = [];
    // 把columns里面的label取出来作为excel的列标题，把prop取出来等下从dataList里面根据作为key取对象中的值
    columns.forEach((column: TableColumn) => {
      if (column.label && column.prop) {
        titleList.push(column.label);
        dataKeyList.push(column.prop as string);
      }
    });

    const excelDataList: string[][] = originalDataList.map(item => {
      const arr = [];
      dataKeyList.forEach(dataKey => {
        let cellValue = item[dataKey];

        // 自动识别 ISO 日期并格式化
        if (
          typeof cellValue === "string" &&
          /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(cellValue)
        ) {
          cellValue = dayjs(cellValue).format("YYYY-MM-DD HH:mm:ss");
        }

        arr.push(cellValue != null ? String(cellValue) : "");
      });
      return arr;
    });

    excelDataList.unshift(titleList);

    const workSheet = utils.aoa_to_sheet(excelDataList);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, excelName);
    writeFile(workBook, `${excelName}.xlsx`);
  }
  // 私有构造函数，防止类被实例化
  private constructor() {}
}
